package com.tistory.wonsama.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

/**
 * 런타임 커맨드 유틸리티
 * @author wonsama
 * @since 2011.12.28
 */
public class WCommandUtil {
	
	public static int MODE_WIN_CMD = 0;
	public static int MODE_LINUX_SH = 1;
	public static int MODE_WIN_CYGWIN = 2;
	
	private static String ENC_DEFAULT = "UTF-8";
	
	/**
	 * 폴더 탐색을 실행한다 
	 * @param pathname 경로 NULL 입력시 현재 경로로 탐색한다 
	 * @param mode 실행 타입 
	 * @return 실행 결과 출력
	 */
	public static String folderExplore(String pathname, int mode){
		String command = "/bin/pwd;/bin/ls -la";
		if( pathname!=null && pathname.trim().equals("") ){
			pathname = null;
		}
		return commander( command , pathname , mode );
	}
	
	
	/**
	 * 커맨드 실행 처리
	 * @param command 커맨드 
	 * @param pathname 시작 위치 (기본값 NULL : 현재 위치가 들어감) 
	 * @param mode 실행 타입 
	 * @return 실행 결과 출력
	 * @since 2011.12.28
	 */
	public static String commander(String command, String pathname, int mode){
		
		//REF -c : close after run command. 
		String[] modeCmd = { "cmd.exe" , "/c" , command };
		String[] modeSh = { "/bin/sh" , "-c" , command };
		String[] modeCygwin = { "C:/cygwin/bin/bash" , "-c" , command};
		
		//순서대로 넣기 바람...
		ArrayList<String[]> cmd = new ArrayList<String[]>();
		cmd.add( modeCmd );cmd.add( modeSh );cmd.add( modeCygwin );
		
		InputStream in;
        BufferedReader br;
        String line;
        StringBuffer sb = new StringBuffer();
        
		try {
			Process proc = pathname==null?Runtime.getRuntime().exec( cmd.get(mode) ):Runtime.getRuntime().exec( cmd.get(mode) , null , new File(pathname) );
			
			in = proc.getInputStream();
			sb.append(getInputStreamMessage( in , ENC_DEFAULT ));
 
            in = proc.getErrorStream();
            sb.append(getInputStreamMessage( in , ENC_DEFAULT ));
			
//			int ev = proc.exitValue();	//0 : OK , 1 : FAIL , ETC : ERR
			proc.waitFor();
			
			return sb.toString();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return "";
	}
	
	/**
	 * GET MESSAGE FROM INPUTSTREAM
	 * @param is INPUTSTREAM
	 * @param encoding CHARACTER ENCODING
	 * @return MESSAGE
	 * @since 2011.12.28
	 */
	private static String getInputStreamMessage(InputStream is, String encoding){

		String readline;
		StringBuffer sb = new StringBuffer();

		try{
			InputStreamReader isr = new InputStreamReader( is , encoding );
			BufferedReader br = new BufferedReader( isr );
			while ( ( readline = br.readLine() ) != null)
			{
				sb.append( readline );
				sb.append( "\n" );
			}
			is.close();
		}catch (Exception e) {
			e.printStackTrace();
		}

		return sb.toString();
	}
	
}
